<?php

namespace app\common\business;

use app\common\lib\Arr;
use app\common\lib\Curl;
use app\common\lib\Status;
use app\common\lib\Str;
use app\common\lib\Time;
use think\Exception;
use think\facade\Cache;

class WorkCollect
{

    public $model = null;

    public function __construct()
    {
        $this->model = new \app\common\model\mysql\WorkCollect();
    }

    public function getListByWhere($where,$page,$limit,$field='*'){
        $where[] = ['status','=',config("status.mysql.table_normal")];
        if ($page!=0 && $limit !=0){
            $list = $this->model->getPageListByWhere($where,$page,$limit,$field);
        }else{
            $list = $this->model->getNormalListByWhere($where,$field);
        }
        if($list->isEmpty()){
            return [];
        }
        return $list->toArray();
    }

    public function getCountByWhere($where,$field='*'){
        $where[] = ['status','=',config("status.mysql.table_normal")];
        $list = $this->model->getNormalListByWhere($where,$field);

        return count($list);
    }

    public function handleData($data,$type)
    {
        if ($data['user_id'] == 0){
            throw new Exception("不存在该用户");
        }
        if ($data['work_id'] == 0){
            throw new Exception("不存在该零活");
        }

        if (!in_array($type,[1,2])){
            throw new Exception("参数错误");
        }

        $workBis = new Work();
        $work = $workBis->getNormalById($data['work_id']);
        if (!$work) {
            throw new Exception("不存在该零活");
        }

        if($workBis->isDepartmentSave($work)){
            $bis = new AdminUser();
        }else{
            $bis = new User();
        }
        $user = $bis->getNormalUserById($data['user_id']);
        if (!$user) {
            throw new Exception("不存在该用户");
        }

        if($work['user_id'] == $data['user_id']){
            throw new Exception("不可对自己发布的零活进行该操作");
        }

        try {
            if($type == 1){
                $res = $this->collect($data);
            }else{
                $res = $this->cancel($data);
            }
        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }
        return $res;
    }

    public function collect($data)
    {
        $where = $data;
        $workCollectInfo = $this->getNormalByWhere($where);
        if (!empty($workCollectInfo)){
            throw new Exception("已收藏该零活，请勿重复操作");
        }

        try {
            $res = $this->model->save($data);
        } catch (\Exception $e) {
            throw new Exception("数据库内部异常");
        }
        return $res;
    }

    public function cancel($data)
    {
        $where = $data;
        $workCollectInfo = $this->getNormalByWhere($where);
        if (empty($workCollectInfo)){
            throw new Exception("未收藏该零活，取消失败");
        }

        $id = $workCollectInfo['id'];
        try {
            $res = $this->model->deleteById($id);
        } catch (\Exception $e) {
            throw new Exception("数据库内部异常");
        }
        return $res;
    }

    public function getNormalByWhere($where,$field='*'): array
    {
        $data = $this->model->getNormalByWhere($where, $field);
        if (!$data) {
            return [];
        }
        return $data->toArray();
    }

    //转义text
    public function resetTextList($list){
        if (empty($list)){
            return [];
        }

        //零活
        $workBis = new Work();
        $workWhere = [
            ['id','in',array_column($list,'work_id')]
        ];
        $workList = $workBis->getListByWhere($workWhere,0,0,'id,department_id,duration,name,longitude,latitude,address,start_time,price,valuation,show_time,process_status,user_id,is_self');
        if (!empty($workList)){$workList = $workBis->resetTextList($workList);}
        $workArr = Arr::getKeyValueByTwoArray($workList,'','id',2);
        foreach ($list as $k=>$v){
            $list[$k]['work'] = $workArr[$v['work_id']] ?? [];
        }
        return $list;
    }

    /**
     * 判断是否收藏
     * @param $userId
     * @param $workId
     * @return int
     */
    public function isCollect($userId,$workId){
        return $this->model->where(['user_id'=>$userId,'work_id'=>$workId])->count();
    }
}
